import { createTool } from '@mastra/core/tools';
import { z } from 'zod';

/**
 * 对话管理工具
 * 专门处理嫌疑人对话的核心逻辑，包括情绪管理、线索透露、角色一致性维护
 */
export const dialogueManagementTool = createTool({
  id: 'dialogue-management',
  description: '对话管理工具，负责处理嫌疑人对话的所有核心逻辑',
  inputSchema: z.object({
    action: z.enum([
      'analyze_question',
      'generate_response',
      'update_emotion',
      'reveal_clue',
      'maintain_consistency',
      'full_dialogue'
    ]).describe('要执行的对话操作类型'),
    
    // 嫌疑人信息
    suspect: z.object({
      id: z.string(),
      name: z.string(),
      personality: z.string(),
      background: z.string(),
      alibi: z.string(),
      secrets: z.array(z.string()).optional(),
      isCulprit: z.boolean().optional(),
      emotionalState: z.string().optional(),
      suspicionLevel: z.number().optional()
    }).describe('嫌疑人基本信息'),
    
    // 对话内容
    question: z.string().describe('侦探的问题'),
    conversationHistory: z.array(z.object({
      role: z.enum(['detective', 'suspect']),
      content: z.string(),
      timestamp: z.string().optional()
    })).optional().describe('对话历史'),
    
    // 游戏上下文
    gameContext: z.object({
      timeRemaining: z.number().optional(),
      discoveredClues: z.array(z.string()).optional(),
      conversationCount: z.number().optional(),
      suspicionLevel: z.number().optional()
    }).optional().describe('游戏上下文信息'),
    
    // 其他参数
    targetEmotion: z.string().optional().describe('目标情绪状态'),
    clueToReveal: z.string().optional().describe('要透露的线索'),
    responseStyle: z.string().optional().describe('回应风格')
  }),
  outputSchema: z.object({
    success: z.boolean().describe('操作是否成功'),
    response: z.string().describe('嫌疑人的回应'),
    emotion: z.string().describe('当前情绪状态'),
    suspicionLevel: z.number().describe('可疑程度 1-10'),
    newClues: z.array(z.object({
      id: z.string(),
      description: z.string(),
      type: z.string(),
      importance: z.number()
    })).describe('新透露的线索'),
    emotionChange: z.object({
      from: z.string(),
      to: z.string(),
      reason: z.string()
    }).optional().describe('情绪变化信息'),
    consistencyCheck: z.object({
      isConsistent: z.boolean(),
      issues: z.array(z.string())
    }).optional().describe('一致性检查结果'),
    nextSuggestions: z.array(z.string()).optional().describe('建议的下一步问题'),
    message: z.string().describe('操作结果消息')
  }),
  execute: async ({ context }) => {
    const { action, suspect, question, conversationHistory = [], gameContext = {} } = context;
    
    try {
      console.log(`对话管理工具执行操作: ${action}`);
      
      switch (action) {
        case 'analyze_question':
          return await analyzeQuestion(question, suspect, conversationHistory);
          
        case 'generate_response':
          return await generateResponse(suspect, question, conversationHistory, gameContext);
          
        case 'update_emotion':
          return await updateEmotion(suspect, question, conversationHistory, context.targetEmotion);
          
        case 'reveal_clue':
          return await revealClue(suspect, question, context.clueToReveal);
          
        case 'maintain_consistency':
          return await maintainConsistency(suspect, conversationHistory);
          
        case 'full_dialogue':
          return await fullDialogueProcess(suspect, question, conversationHistory, gameContext);
          
        default:
          return {
            success: false,
            response: '未知的对话操作类型',
            emotion: 'confused',
            suspicionLevel: 5,
            newClues: [],
            message: `未知的操作类型: ${action}`
          };
      }
    } catch (error) {
      console.error(`对话管理工具操作失败 [${action}]:`, error);
      return {
        success: false,
        response: '我现在有些困惑，能重新问一遍吗？',
        emotion: 'confused',
        suspicionLevel: 5,
        newClues: [],
        message: `操作失败: ${error instanceof Error ? error.message : '未知错误'}`
      };
    }
  },
});

/**
 * 分析问题类型和意图
 */
async function analyzeQuestion(question: string, suspect: any, conversationHistory: any[]) {
  const questionTypes = {
    alibi: ['在哪里', '什么时候', '时间', '地点', '不在场'],
    motive: ['为什么', '动机', '原因', '关系', '矛盾'],
    evidence: ['看到', '听到', '证据', '物品', '现场'],
    personal: ['你是', '背景', '工作', '家庭', '个人'],
    accusation: ['是你', '凶手', '杀了', '做的', '承认']
  };
  
  let questionType = 'general';
  let intensity = 1;
  
  // 分析问题类型
  for (const [type, keywords] of Object.entries(questionTypes)) {
    if (keywords.some(keyword => question.includes(keyword))) {
      questionType = type;
      break;
    }
  }
  
  // 分析问题强度
  if (question.includes('？') || question.includes('?')) intensity += 1;
  if (question.includes('！') || question.includes('!')) intensity += 2;
  if (question.length > 50) intensity += 1;
  
  // 根据问题类型确定情绪反应
  const emotionMap: { [key: string]: string } = {
    alibi: suspect.isCulprit ? 'nervous' : 'calm',
    motive: suspect.isCulprit ? 'defensive' : 'confused',
    evidence: 'thoughtful',
    personal: 'calm',
    accusation: suspect.isCulprit ? 'angry' : 'shocked'
  };
  
  const targetEmotion = emotionMap[questionType] || 'calm';
  
  return {
    success: true,
    response: `问题分析完成：类型为${questionType}，强度为${intensity}`,
    emotion: targetEmotion,
    suspicionLevel: suspect.suspicionLevel || 5,
    newClues: [],
    message: `问题类型: ${questionType}, 建议情绪: ${targetEmotion}`
  };
}

/**
 * 生成嫌疑人回应
 */
async function generateResponse(suspect: any, question: string, conversationHistory: any[], gameContext: any) {
  const { timeRemaining = 180, discoveredClues = [], conversationCount = 0 } = gameContext;
  
  // 根据嫌疑人类型和问题生成回应
  let response = '';
  let emotion = suspect.emotionalState || 'calm';
  let suspicionLevel = suspect.suspicionLevel || 5;
  const newClues = [];
  
  // 分析问题关键词
  const isAlibiQuestion = question.includes('在哪') || question.includes('时间') || question.includes('地点');
  const isMotiveQuestion = question.includes('为什么') || question.includes('动机') || question.includes('关系');
  const isEvidenceQuestion = question.includes('看到') || question.includes('听到') || question.includes('证据');
  const isAccusation = question.includes('是你') || question.includes('凶手') || question.includes('杀了');
  
  if (isAccusation) {
    // 处理直接指控
    if (suspect.isCulprit) {
      response = generateCulpritDefense(suspect, question);
      emotion = 'angry';
      suspicionLevel = Math.min(suspicionLevel + 2, 10);
    } else {
      response = generateInnocentShock(suspect, question);
      emotion = 'shocked';
      suspicionLevel = Math.max(suspicionLevel - 1, 1);
    }
  } else if (isAlibiQuestion) {
    // 处理不在场证明问题
    response = generateAlibiResponse(suspect, question);
    emotion = suspect.isCulprit ? 'nervous' : 'calm';
    
    // 可能透露时间线索
    if (Math.random() < 0.3) {
      newClues.push({
        id: `clue-timeline-${Date.now()}`,
        description: `${suspect.name}提供了详细的时间线信息`,
        type: 'testimony',
        importance: 3
      });
    }
  } else if (isMotiveQuestion) {
    // 处理动机问题
    response = generateMotiveResponse(suspect, question);
    emotion = suspect.isCulprit ? 'defensive' : 'confused';
    
    // 可能透露关系线索
    if (Math.random() < 0.4) {
      newClues.push({
        id: `clue-relationship-${Date.now()}`,
        description: `${suspect.name}透露了与受害者的关系信息`,
        type: 'circumstantial',
        importance: 4
      });
    }
  } else if (isEvidenceQuestion) {
    // 处理证据问题
    response = generateEvidenceResponse(suspect, question);
    emotion = 'thoughtful';
    
    // 可能透露证据线索
    if (Math.random() < 0.5) {
      newClues.push({
        id: `clue-evidence-${Date.now()}`,
        description: `${suspect.name}提供了重要的证据信息`,
        type: 'physical',
        importance: 5
      });
    }
  } else {
    // 处理一般问题
    response = generateGeneralResponse(suspect, question);
    emotion = 'calm';
  }
  
  // 根据时间压力调整情绪
  if (timeRemaining < 60) {
    emotion = intensifyEmotion(emotion);
    suspicionLevel = Math.min(suspicionLevel + 1, 10);
  }
  
  // 根据对话次数调整
  if (conversationCount > 5) {
    emotion = 'tired';
    response += ' 我们已经谈了很久了...';
  }
  
  return {
    success: true,
    response,
    emotion,
    suspicionLevel,
    newClues,
    message: '回应生成成功'
  };
}

/**
 * 更新情绪状态
 */
async function updateEmotion(suspect: any, question: string, conversationHistory: any[], targetEmotion?: string) {
  const currentEmotion = suspect.emotionalState || 'calm';
  const newEmotion = targetEmotion || determineEmotionFromQuestion(question, suspect);
  
  const emotionChange = {
    from: currentEmotion,
    to: newEmotion,
    reason: `基于问题"${question}"的情绪反应`
  };
  
  return {
    success: true,
    response: `情绪从${currentEmotion}变为${newEmotion}`,
    emotion: newEmotion,
    suspicionLevel: suspect.suspicionLevel || 5,
    newClues: [],
    emotionChange,
    message: '情绪状态更新成功'
  };
}

/**
 * 透露线索
 */
async function revealClue(suspect: any, question: string, clueToReveal?: string) {
  const clue = clueToReveal || generateRandomClue(suspect, question);
  
  const newClues = [{
    id: `clue-revealed-${Date.now()}`,
    description: clue,
    type: 'testimony',
    importance: Math.floor(Math.random() * 5) + 1
  }];
  
  return {
    success: true,
    response: `关于这个问题，我想起了一些事情...${clue}`,
    emotion: 'thoughtful',
    suspicionLevel: suspect.suspicionLevel || 5,
    newClues,
    message: '线索透露成功'
  };
}

/**
 * 维护角色一致性
 */
async function maintainConsistency(suspect: any, conversationHistory: any[]) {
  const issues = [];
  
  // 检查回应是否与角色设定一致
  // 这里可以添加更复杂的一致性检查逻辑
  
  const consistencyCheck = {
    isConsistent: issues.length === 0,
    issues
  };
  
  return {
    success: true,
    response: '一致性检查完成',
    emotion: suspect.emotionalState || 'calm',
    suspicionLevel: suspect.suspicionLevel || 5,
    newClues: [],
    consistencyCheck,
    message: `一致性检查${issues.length === 0 ? '通过' : '发现问题'}`
  };
}

/**
 * 完整对话处理流程
 */
async function fullDialogueProcess(suspect: any, question: string, conversationHistory: any[], gameContext: any) {
  // 1. 分析问题
  const analysis = await analyzeQuestion(question, suspect, conversationHistory);
  
  // 2. 生成回应
  const response = await generateResponse(suspect, question, conversationHistory, gameContext);
  
  // 3. 更新情绪
  const emotionUpdate = await updateEmotion(suspect, question, conversationHistory, response.emotion);
  
  // 4. 检查一致性
  const consistency = await maintainConsistency(suspect, conversationHistory);
  
  return {
    success: true,
    response: response.response,
    emotion: emotionUpdate.emotion,
    suspicionLevel: response.suspicionLevel,
    newClues: response.newClues,
    emotionChange: emotionUpdate.emotionChange,
    consistencyCheck: consistency.consistencyCheck,
    nextSuggestions: generateNextQuestionSuggestions(suspect, question),
    message: '完整对话处理成功'
  };
}

// 辅助函数
function generateCulpritDefense(suspect: any, question: string): string {
  const defenses = [
    '这是诬陷！我绝对没有做过这种事！',
    '你没有证据证明是我做的！',
    '我为什么要这么做？这对我有什么好处？',
    '你应该去调查其他人，而不是把时间浪费在我身上！'
  ];
  return defenses[Math.floor(Math.random() * defenses.length)];
}

function generateInnocentShock(suspect: any, question: string): string {
  const shocks = [
    '什么？你怎么能这样说我！',
    '这太荒谬了！我怎么可能做这种事！',
    '我完全震惊了，你竟然会怀疑我！',
    '这一定是误会，我是无辜的！'
  ];
  return shocks[Math.floor(Math.random() * shocks.length)];
}

function generateAlibiResponse(suspect: any, question: string): string {
  return `关于我的行踪，${suspect.alibi}。我可以提供更多细节如果你需要的话。`;
}

function generateMotiveResponse(suspect: any, question: string): string {
  if (suspect.isCulprit) {
    return '我和受害者没有什么特别的矛盾，我们的关系很正常。';
  } else {
    return `我和受害者的关系确实有些复杂，但这不意味着我会伤害他们。`;
  }
}

function generateEvidenceResponse(suspect: any, question: string): string {
  const responses = [
    '我确实注意到了一些不寻常的事情...',
    '现在你这么问，我想起了一些细节。',
    '关于证据，我可能知道一些有用的信息。'
  ];
  return responses[Math.floor(Math.random() * responses.length)];
}

function generateGeneralResponse(suspect: any, question: string): string {
  const responses = [
    '这是个有趣的问题，让我想想...',
    '我不太确定这个问题的答案。',
    '你为什么要问这个？',
    '我觉得这个问题很重要吗？'
  ];
  return responses[Math.floor(Math.random() * responses.length)];
}

function intensifyEmotion(emotion: string): string {
  const intensityMap: { [key: string]: string } = {
    calm: 'nervous',
    nervous: 'anxious',
    thoughtful: 'worried',
    confused: 'frustrated',
    defensive: 'angry'
  };
  return intensityMap[emotion] || emotion;
}

function determineEmotionFromQuestion(question: string, suspect: any): string {
  if (question.includes('杀') || question.includes('凶手')) {
    return suspect.isCulprit ? 'angry' : 'shocked';
  }
  if (question.includes('为什么') || question.includes('动机')) {
    return 'defensive';
  }
  if (question.includes('证据') || question.includes('看到')) {
    return 'thoughtful';
  }
  return 'calm';
}

function generateRandomClue(suspect: any, question: string): string {
  const clues = [
    '我记得那天有人行为很奇怪',
    '现场确实有一些不寻常的物品',
    '我听到了一些争吵声',
    '有人在案发时间附近出现过'
  ];
  return clues[Math.floor(Math.random() * clues.length)];
}

function generateNextQuestionSuggestions(suspect: any, currentQuestion: string): string[] {
  return [
    '能详细说说你的不在场证明吗？',
    '你和受害者的关系如何？',
    '你在现场看到了什么？',
    '还有其他人知道这件事吗？'
  ];
}
